package com.tjsinfo.tjsoa.articles.action;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.tjsinfo.tjsoa.articles.bo.ITArticlesManage;
import com.tjsinfo.tjsoa.articles.bo.IViewManage;
import com.tjsinfo.tjsoa.articles.bo.ManageSuperAction;
import com.tjsinfo.tjsoa.articles.bo.TArticlesRolesManage;
import com.tjsinfo.tjsoa.articles.bo.TArticlesUserManage;
import com.tjsinfo.tjsoa.articles.vo.TIndexArticles;
import com.tjsinfo.tjsoa.articles.vo.TIndexView;
import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.common.PaginationSupport;

import com.tjsinfo.tjsoa.system.vo.User; 

public class ArticlesManageAction extends ManageSuperAction {
	
	private TArticlesRolesManage articlesRolesManage;
	private TArticlesUserManage articlesUserManage;
	private ITArticlesManage articlesManage;
	private IViewManage articlesViewMange;
	
	public ITArticlesManage getArticlesManage() {
		return articlesManage;
	}
	public void setArticlesManage(ITArticlesManage articlesManage) {
		this.articlesManage = articlesManage;
	}
	public TArticlesUserManage getArticlesUserManage() {
		return articlesUserManage;
	}
	public void setArticlesUserManage(TArticlesUserManage articlesUserManage) {
		this.articlesUserManage = articlesUserManage;
	}
	public TArticlesRolesManage getArticlesRolesManage() {
		return articlesRolesManage;
	}
	public void setArticlesRolesManage(TArticlesRolesManage articlesRolesManage) {
		this.articlesRolesManage = articlesRolesManage;
	}
	public IViewManage getArticlesViewMange() {
		return articlesViewMange;
	}
	public void setArticlesViewMange(IViewManage articlesViewMange) {
		this.articlesViewMange = articlesViewMange;
	}
/**
 * 用户ArticlesList、ArticlesSave、ArticlesUpdate页面中根据CID获取栏目名称
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
	public ActionForward getRoleName(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception {
		
		Integer cid = Integer.parseInt(request.getParameter("cid"));
 		try {
 			JSONArray array	 = new JSONArray();
 			JSONObject jsonObject = new JSONObject();  
	 		jsonObject.put("cname",articlesRolesManage.findById(cid).getName());
	 		array.put(jsonObject);
 			response.getWriter().print(array);    //[{"cname":"新闻中心"}]
 		} catch (IOException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		} 
		return null;
	}	
	
	
	
	/**
	 * 取得文章列表     根据栏目ID(cid)以及当前登录用户信息，获取本栏目中当前用户可以修改删除的文章列表
	 * @return
	 */
	public ActionForward getArticlesList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception {
		
		// 根据用户及cid查找当前栏目文章列表 	
		try {
			Integer cid = Integer.parseInt(request.getParameter("cid"));
			User sessionUser = ToolKit.getSessionUser(request); //从session中取得当前登录用户
			if (sessionUser !=null) //如果没有用户session则不显示维护列表
			{
				String strSearch=request.getParameter("search");
				if (strSearch==null){
					strSearch="";
		 		}else{
		 			strSearch=URLDecoder.decode(URLDecoder.decode(strSearch,"UTF-8"),"UTF-8");
		 		}
		 		String strstart=request.getParameter("start");  //列表分页显示当前页开始条数
		 		if (strstart==null){
		 			strstart="0";
		 			}
		 		String strlimit=request.getParameter("limit");  //列表分页显示每页显示条数
		 		if (strlimit==null){
		 			strlimit="20";
		 			}
		 		PaginationSupport ps;
		 		if (CisUserShow(cid)){               //对于isusershow设置为1的栏目需要根据分用户进行筛选
		 			Integer userId = ToolKit.getSessionUser(request).getUser_id(); //从session中取得当前登录用户userId
	 				ps = articlesManage.findByCidSearch(cid,userId,strSearch,strstart,strlimit);
		 		}else{
	 				ps = articlesManage.findByCidSearch(cid,strSearch,strstart,strlimit);
		 		}
		 		Integer articlelistall = ps.getTotalCount();//得到文章总数
		 		List<TIndexArticles> articlelistpage = ps.getItems();//将分页对象中获得object列表转换成Articles列表
			
		 		// 输出查到的文章列表数据	
		 		JSONArray array	 = new JSONArray();
		 			for (TIndexArticles articlesL : articlelistpage) {
		 				JSONObject object = new JSONObject(articlesL);
		 				array.put(object);
		 			}
			 		JSONObject jsonObject = new JSONObject();  
			 		jsonObject.put("totalCount",articlelistall);  //结果总数
			 		jsonObject.put("aricleslist", array);   //当前页文章列表
		 			response.getWriter().print(jsonObject);
			}
	 	   	} catch (IOException e) {
		 			// TODO Auto-generated catch block
		 			e.printStackTrace();
 		} 
		 		return null;
	}
	

	/**
	 * 进入新建文章页面前数据处理
	 * @return
	 */
	public ActionForward toAddArticles(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		//2lbj_get UserID
		User sessionUser=ToolKit.getSessionUser(request);
		//根据用户session判断用户是否正常登录，如没有session则弹出登录提示框
		if (sessionUser!=null){    
				Integer cid = Integer.parseInt(request.getParameter("cid")); //从路径中获取cid参数并将其转换为int
				TIndexView roleView = articlesViewMange.findByICid(cid);
				request.getSession().setAttribute("cnamepinyin", roleView.getPinYin()); //根据cid获取栏目拼音，并将其存入session，用于ckfinder判断显示及保存路径
				request.getSession().setAttribute("userid", sessionUser.getUser_id());  //获取userid存入session，用于上传附件时附件文件名中能够体现用户id
				request.setAttribute("ctype", roleView.getShowView()); //根据cid获取栏目显示类型，并向页面传递该参数
				String cname=String.valueOf(request.getParameter("cname"));
				request.setAttribute("cname", cname); //从链接中获取栏目名称，并向页面传递该参数
			    return mapping.findForward(TOADDOK);
		}else{
			request.setAttribute("message", "logerr");
			return mapping.findForward(SHOWMESSAGE);
		}
	}
	
	/**
	 * 增加文章
	 * @return
	 */
	
	public ActionForward addArticles(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
	
		//2lbj_get UserID
		User sessionUser=ToolKit.getSessionUser(request);
		//根据用户session判断用户是否正常登录，如果未登录不保存记录，也不保存html正文
		if (sessionUser!=null){                      
	        //获取uuid
			UUID uuid = UUID.randomUUID();
			String uid = uuid.toString().replace("-", "");
			//获取当前日期作为建立日期
			java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String strdate=format1.format(new Date());
			//从表单获取各栏目录入信息
			DynaActionForm articlesForm=(DynaActionForm)form;
				 String _title=(String)articlesForm.get("_title");
				 String _author=(String)articlesForm.get("_author");
				 String _shortTitle=(String)articlesForm.get("_shortTitle");
				 String _url=(String)articlesForm.get("_url");
				 String _keywords=(String)articlesForm.get("_keywords");
				 String _smallContent=(String)articlesForm.get("_smallContent");
				 Integer _showOrder= Integer.parseInt(articlesForm.get("_showOrder").toString());
				 String content=(String)articlesForm.get("content");
				 
				 String _smallPicUrl=(String)articlesForm.get("_smallPicUrl");				 
				 String _availableDate=(String)articlesForm.get("_availableDate");
				 String _uploadFile=(String)articlesForm.get("_uploadFile");
				 Integer cid = (Integer)articlesForm.get("cid");
				 String _isfile = (String)articlesForm.get("_isfile");
	             
			//给各个字段赋值
			TIndexArticles al = new TIndexArticles();
		    al.setSmallPic(convertSmallPicUrl(_smallPicUrl));//缩略图，使用convertSmallPicUrl对_smallPicUrl进行处理
		    al.setTitle(_title); //标题
		    al.setAuthor(_author);//作者
		    al.setShortTitle(_shortTitle);//短标题
		    al.setUrl(_url);//超链接
			al.setCreateDate(strdate);//建立日期
		    al.setAvailableDate(_availableDate);//有效时间
			al.setShowOrder(_showOrder);//显示顺序
	        al.setUuid(uid);//uuid
			al.setKeyWord(_keywords); //关键字
			al.setSmallContent(_smallContent); //摘要
	//		al.setMainContent(Jsoup.parse(content,"UTF-8").text());  //内容，字段较短暂不保存数据
			al.setCid(cid);  //栏目id
			al.setUploadFile(_uploadFile);  //附件
			
			String ctype=getCtype(cid);
			if (_isfile.indexOf('1')>0 & !_uploadFile.contains("</a>")){
				al.setIsFile("0");
			}else{
				al.setIsFile(_isfile);
			}
//	        if (ctype.indexOf('z')>0 & _uploadFile.contains("</a>")) {  //如果该栏目类型中包含“z”，说明该栏目中的文章点击链接时需要直接打开附件，则将isfile字段设为1，否则设为0
//	        	al.setIsFile("1");     
//	        }else if(ctype.indexOf('b')>0)  //如果栏目类型中包含“b”，以大表格模式显示isfile字段存2
//	        {
//	        	al.setIsFile("2");
//	        }else if(ctype.indexOf('h')>0)  //如果栏目类型中包含“h”，以超大表格模式显示isfile字段存3
//	        {
//	        	al.setIsFile("3");
//	        }else if(ctype.indexOf('d')>0)  //如果栏目类型中包含“d”，以超word插件显示isfile字段存4
//	        {
//	        	al.setIsFile("4");
//	        }else{
//	        	al.setIsFile("0");
//	        }
	        Integer userId = ToolKit.getSessionUser(request).getUser_id(); //当前用户ID
	   	    al.setUserId(userId);  //当前用户
	   	    al.setUserName(ToolKit.getSessionUser(request).getUsername());
			articlesManage.save(al);//保存   
			uploadHtmlFile(uid,content,request);//上传正文html
			String stype="yes";
			if(ctype.indexOf('n')>0){stype="no";}
			request.setAttribute("type", stype);
			request.setAttribute("cid", cid);
			request.setAttribute("message", "save");
        }else{
        	request.setAttribute("message", "logerr");  //由于用户session不存在，因此提示登录状态异常
        }
		return mapping.findForward(SHOWMESSAGE);
	}
	
	/**
	 * 跳转到更新文章页面
	 * @return
	*/
	public ActionForward toUpdateArticles(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		
		//2lbj_get UserID
		User sessionUser=ToolKit.getSessionUser(request);
		//根据用户session判断用户是否正常登录，如没有session则弹出登录提示框
		if (sessionUser!=null){                      
		
			//通过页面传递的uuid查找文章
			String articles_uuid = request.getParameter("articles_uuid");
		    TIndexArticles articles = articlesManage.findByID(articles_uuid);
		    
		    //将文章对象传递给页面
			request.setAttribute("articles", articles);
			//通过cid获取栏目名称并转换为拼音，存入session
			Integer cid = articles.getCid();    //获取cid
			TIndexView roleView = articlesViewMange.findByICid(cid);
			request.getSession().setAttribute("cnamepinyin", roleView.getPinYin()); //根据cid获取栏目拼音，并将其存入session，用于ckfinder判断显示及保存路径
			request.getSession().setAttribute("userid", sessionUser.getUser_id());  //获取userid存入session，用于上传附件时附件文件名中能够体现用户id
			request.setAttribute("ctype", roleView.getShowView()); //根据cid获取栏目显示类型，并向页面传递该参数

//			request.setAttribute("ctype", getCtype(cid));  //根据cid获取栏目显示类型，并将其传递给页面
			request.setAttribute("content", downloadHtmlFile(articles_uuid,request)); //从html文件中读取正文，并将正文传递给页面
			String cname=String.valueOf(request.getParameter("cname"));
			request.setAttribute("cname", cname); //从链接中获取栏目名称，并向页面传递该参数				
			return mapping.findForward(TOUPDATEOK);
		}else{
			request.setAttribute("message", "logerr");  //由于用户session不存在，因此提示登录状态异常
			return mapping.findForward(SHOWMESSAGE);
		}
	} 
	
	/**
	 * 更新文章
	 * @return
	 */
	public ActionForward updateArticles(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		
		//2lbj_get UserID
		User sessionUser=ToolKit.getSessionUser(request);
		//根据用户session判断用户是否正常登录，如没有session则弹出登录提示框
		if (sessionUser!=null){                      
				//从表单获取各栏目录入信息		
				DynaActionForm articlesForm=(DynaActionForm)form;
				
				 String articles_uuid=(String)articlesForm.get("articles_uuid");
				 TIndexArticles al = articlesManage.findByID(articles_uuid);
				 String path = request.getContextPath();
				 String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path ;
				 
				 Integer cid = (Integer)articlesForm.get("cid");
				 String _title=(String)articlesForm.get("_title");
				 String _author=(String)articlesForm.get("_author");
				 String _shortTitle=(String)articlesForm.get("_shortTitle");
				 String _url=(String)articlesForm.get("_url");
				 String _keywords=(String)articlesForm.get("_keywords");
				 String _smallContent=(String)articlesForm.get("_smallContent");
				 Integer _showOrder=(Integer)articlesForm.get("_showOrder");
				 String content=(String)articlesForm.get("content");
				 
				 String _PicUrl=(String)articlesForm.get("_smallPicUrl");
				 if(_PicUrl.contains("null")){
					 _PicUrl="";
				 }else{
					 _PicUrl=(String)articlesForm.get("_smallPicUrl");	
				 }					 
				 String _uploadFile=(String)articlesForm.get("_uploadFile");
				 String _availableDate=(String)articlesForm.get("_availableDate");
				 String _isfile = (String)articlesForm.get("_isfile");
			    
				//向各栏目赋值
			    al.setTitle(_title); //标题
			    al.setAuthor(_author);//作者
			    al.setShortTitle(_shortTitle);//短标题
			    al.setUrl(_url);//超链接
			    al.setAvailableDate(_availableDate);  //有效时间
				al.setShowOrder(_showOrder); //显示顺序
				al.setKeyWord(_keywords); //关键字
		        al.setSmallPic(convertSmallPicUrl(_PicUrl));//缩略图，使用convertSmallPicUrl对_smallPicUrl进行处理);
		        al.setUploadFile(_uploadFile); //附件
		        String ctype=getCtype(cid);
		    	if (_isfile.indexOf('1')>0 & !_uploadFile.contains("</a>")){
					al.setIsFile("0");
				}else{
					al.setIsFile(_isfile);
				}

//		        if (ctype.indexOf('z')>0 & _uploadFile.contains("</a>")) {  //如果该栏目类型中包含“z”，说明该栏目中的文章点击链接时需要直接打开附件，则将isfile字段设为1，否则设为0
//		        	al.setIsFile("1");
//		        }else if(ctype.indexOf('b')>0)  //如果栏目类型中包含“b”，以超大表格模式显示isfile字段存2
//		        {
//		        	al.setIsFile("2");
//		        }else if(ctype.indexOf('h')>0)  //如果栏目类型中包含“h”，以超大表格模式显示isfile字段存3
//		        {
//		        	al.setIsFile("3");
//		        }else{
//		        	al.setIsFile("0");
//		        }
		        al.setSmallContent(_smallContent);
		//		al.setMainContent(Jsoup.parse(content,"UTF-8").text());
				articlesManage.update(al);
				uploadHtmlFile(al.getUuid(),content,request);  //上传正文html
				String stype="yes";
				if(ctype.indexOf('n')>0){stype="no";}
				request.setAttribute("type", stype);//若type=“no”，则返回列表页时不显示删除按钮
				request.setAttribute("cid", cid);
				request.setAttribute("message", "update");
		}else{
			request.setAttribute("message", "logerr"); //由于用户session不存在，因此提示登录状态异常
		}
		return mapping.findForward(SHOWMESSAGE);
	}
	
/**
 *  删除文章
 */	
	public ActionForward deleteArticles(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception{
		String articles_uuid = request.getParameter("articles_uuid");
		articlesManage.deleteArticles(articles_uuid);
		return null;
	}

	/**
	 * 获取栏目拼音字符串
	 * @return
	 */
//	private String getCnamepinyin(Integer cid)
//	{
//		TIndexView roleView = articlesViewMange.findByICid(cid);
//		return roleView.getPinYin();
//	}
	
	/**
	 * 获取栏目显示类型
	 * @return
	 */
	private String getCtype(Integer cid)
	{
		TIndexView roleView = articlesViewMange.findByICid(cid);
		return roleView.getShowView();
	}
	
	/**
	 * 处理缩略图html字符串，返回图片路径及文件名
	 */
	private String convertSmallPicUrl(String _smallPicUrl)
	{ 
		String _smallPic = null;
		if(!(_smallPicUrl==null || "".equals(_smallPicUrl))){
			Document doc = Jsoup.parse(_smallPicUrl);
			Element img = doc.select("img[src]").first();
			try{
				_smallPic = img.attr("src");
			} catch (Exception e) {
				_smallPic = null;
			}
		}
	    return _smallPic;
	}


/**
 * 判断栏目IsUserShow字段值
 * @param cid
 * @return 如果字段值为“1”返回true 否则返回false
 */
	private Boolean CisUserShow(Integer cid) {
		// TODO Auto-generated method stub
		TIndexView roleView = articlesViewMange.findByICid(cid);
		Boolean isShow;
		if ("1".equals(roleView.getIsUserShow())) {isShow=true;}
		else {isShow= false;} 
		return isShow;
	}
	
	/**
	 *  跳转到栏目显示设置页面
	 * @param cid
	 */	
		public ActionForward toUpdateView(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)throws Exception{
			String cid = request.getParameter("cid");
			User sessionUser = ToolKit.getSessionUser(request); //从session中取得当前登录用户
			if (sessionUser.getUser_id()==1 || sessionUser.getUsername().indexOf("管理员")>-1) //如果用户是admin才显示维护列表
			{
				request.setAttribute("cid", cid);
				request.setAttribute("ctype", getCtype(Integer.parseInt(cid)));
				String cname=String.valueOf(request.getParameter("cname"));
				request.setAttribute("cname", cname); //从链接中获取栏目名称，并向页面传递该参数				
				return mapping.findForward("articlesSet");
			}else {
				request.setAttribute("cid", Integer.parseInt(cid));
				request.setAttribute("message", "back");
				return mapping.findForward(SHOWMESSAGE);
			}
		}
		
	/**
	*  保存栏目显示设置
	* @param cid
	*/	
	public ActionForward updateView(ActionMapping mapping, ActionForm form,
					HttpServletRequest request, HttpServletResponse response)throws Exception{
				Integer  cid = Integer.parseInt(request.getParameter("cid"));
				String ctype = request.getParameter("ctype");
				TIndexView roleView = articlesViewMange.findByICid(cid);
				roleView.setShowView(ctype);
				articlesViewMange.update(roleView);
				request.setAttribute("cid", cid);
				request.setAttribute("message", "save");
				return mapping.findForward(SHOWMESSAGE);
			}	
	
}

